
import customer from '@/api/crm/customerAPI'
export default{
  props: {
    param: Object,
    updateOpt: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      type: '',
      list: [],
      detailParam: this.param || {}
    }
  },
  methods: {
    cancel () {
      this.$refs.contactsDrawer.close()
    },
    handlePrimaryContact (index, row) {
      if (this.updateOpt) {
        const params = {id: row.id, primaryContacts: 1, customerCode: row.customerCode}
        customer.updateContactsInfosAPI(params).then(res => {
          this.getContactsList()
        })
      } else {
        this.list[index].primaryContacts = 1
        this.refresh(index)
      }
    },
    handleSaveContacts (info, index) {
      if (this.updateOpt) {
        // 更新客户保存联系人
        const contactInfo = {...info}
        delete contactInfo.updateTime
        if (contactInfo.id && contactInfo.id !== null) {
          customer.updateContactsInfosAPI(contactInfo).then(res => {
            this.getContactsList(contactInfo.customerCode)
            this.cancel()
          })
        } else {
          customer.addContactsInfosAPI(contactInfo).then(res => {
            this.getContactsList(contactInfo.customerCode)
            this.cancel()
          })
        }
      } else {
        // 新增客户保存联系人
        // 判断是否更新 更新时 index=-1
        const isUpdate = this.list && this.list.length > 0 && index >= 0
        // 更新已有主要联系人信息
        if (info.primaryContacts === 1 && this.list && this.list.length > 0) {
          this.refresh(index)
        }
        if (isUpdate) {
          // 更新联系人
          this.list[index] = {...info}
          this.tableKey = Math.random()
        } else {
          // 新增联系人
          this.list.unshift(info)
          // 滚动轮
          this.$emit('scroll-to', this.list.length)
        }
        this.cancel()
      }
      // 关闭窗口
      // this.$bus.emit('open-rightPanel', false)
    },
    handleDeleteContacts (index, row) {
      this.$msgBox.confirm('确认删除联系人-【' + row.contactsName + '】？', () => {
        if (this.updateOpt) {
          customer.deleteContactsInfosAPI(row.id).then(res => {
            this.list.splice(index, 1)
          })
        } else {
          this.list.splice(index, 1)
        }
      })
    },
    getContactsList (customerCode) {
      if (this.type === 'contacts' && this.updateOpt) {
        if (!customerCode || customerCode === undefined) {
          customerCode = this.detailParam.customerCode
        }
        customer.getCustomerContactsListAPI(customerCode).then(res => {
          this.list = res.data || []
        })
      }
    },
    refresh (index) {
      for (let i = 0; i < this.list.length; i++) {
        if (index !== i && this.list[i].primaryContacts === 1) {
          this.list[i].primaryContacts = 0
          break
        }
      }
    }
  }
}
